<template>
  <AuModal
    v-model="showPopup"
    :title="title"
    :width="460"
    :padding="false"
    :show-minimize="showMinimize"
    v-bind="modalProps"
    @handleConfirm="formRef.submit()"
    @close="close"
  >
    <div class="pt-[30px] pb-[12px] pl-[20px] pr-[40px] flex justify-center">
      <AuForm
        ref="formRef"
        :formData="formData"
        :formList="formList"
        :isInline="false"
        :hiddenBtn="true"
        :hasUnfold="false"
        labelWidth="86px"
        class="!w-[286px]"
        v-bind="formProps"
        @change="formChange"
        @submit="handleForm"
      >
        <template v-for="slotKey in formSlotList" v-slot:[slotKey]="data">
          <slot :name="slotKey" v-bind="data" />
        </template>

        <template #footer_left>
          <slot name="footer_left" />
        </template>
      </AuForm>
    </div>

    <template #footer_left>
      <slot name="footer_left" />
    </template>
  </AuModal>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, useSlots, watch } from "vue";
import { AuForm } from "@/components/AuForm";
import AuModal from "./index.vue";
import { BaseProps, inputProps, selectProps } from "@/components/AuForm/type";
import { defProps } from "@/components/AuForm/src/tools";

defineOptions({
  name: "FormModal"
});

interface Props {
  modelValue: boolean;
  title: string;
  formList: (BaseProps | selectProps | inputProps | any)[];
  formData?: Record<string, any>;
  showMinimize?: boolean;
  modalProps?: any;
  formProps?: any;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: "",
  showMinimize: false,
  formList: () => []
});
const emit = defineEmits(["handleConfirm", "formChange", "update:modelValue"]);
const slots = useSlots();

// region 声明ref变量集合
const showPopup = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  }
});
const formSlotList = ref([]);

const formRef = ref();
// endregion

// region 公共方法的集合
// endregion

// region 组件事件的集合
const handleForm = (data: Record<string, any>) => {
  emit("handleConfirm", data);
};
const formChange = (data: Record<string, any>) => {
  emit("formChange", data);
};

const close = () => {
  formRef.value.reset();
  emit("update:modelValue", false);
};

const getFormSlotList = () => {
  for (const slotNameKey in slots) {
    if (slotNameKey.endsWith("_behind") || slotNameKey.endsWith("_label")) {
      formSlotList.value.push(slotNameKey);
    }
  }
};
// endregion

// region 组件事件的集合
getFormSlotList();
onMounted(() => {});

defineExpose({
  getFormData: () => formRef.value.getFormData(),
  reset: () => formRef.value.reset(),
  setFormProps: (key: string | string[], option: any) =>
    formRef.value.setFormProps(key, option),
  setFormData: (option: any) => formRef.value.setFormData(option)
});
// endregion
</script>
